<template>
  <div>
    <canvas id="myCanvas" width="640" height="360"></canvas>
  </div>
</template>

<script>
import { MP4Clip } from '@webav/av-cliper';

export default {
  name: 'VideoRenderPage',
  mounted() {
    const canvas = document.getElementById('myCanvas');
    const mp4Url = require('@/assets/video/4.mp4');
    this.renderVideoToCanvas(mp4Url, canvas);
  },
  methods: {
    async renderVideoToCanvas(mp4Url, canvas) {
      const ctx = canvas.getContext('2d');
      try {
        // 传入一个 mp4 文件流即可初始化
        const clip = new MP4Clip((await fetch(mp4Url)).body);
        console.log('clip: ', clip);
        await clip.ready;

        let time = 0;

        function renderFrame() {
          return new Promise(async (resolve) => {
            const { state, video: videoFrame } = await clip.tick(time);
            if (state === 'done') {
              clip.destroy();
              resolve();
              return;
            }
            if (videoFrame != null && state === 'success') {
              ctx.clearRect(0, 0, canvas.width, canvas.height);
              // 绘制到 Canvas
              ctx.drawImage(videoFrame, 0, 0, videoFrame.codedWidth, videoFrame.codedHeight);
              // 注意，用完立即 close
              videoFrame.close();
            }
            // 时间单位是 微秒，所以差不多每秒取 30 帧，丢掉多余的帧
            time += 33000;
            requestAnimationFrame(() => {
              resolve(renderFrame());
            });
          });
        }

        await renderFrame();
      } catch (error) {
        console.error('视频渲染出错:', error);
      }
    },
  },
};
</script>

